package com.ml.fdba.core.service;

import com.ml.fdba.core.entity.TableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class OutService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private TableList tableList;

    public List queryTableList(String tableName, Map condition){
        String conditionSql = "";
        if(condition!=null){
            conditionSql =  handleCondition(condition, tableList.getTableFields(tableName));
        }
        String sql = "select * from "+ tableName + conditionSql;
        return jdbcTemplate.queryForList(sql);
    }

    private String handleCondition(Map condition, List<TableList.Table.Field> fieldList){
        String sql = " where 1=1 ";
        Set keySet =  condition.keySet();
        Iterator iterator = keySet.iterator();

        while (iterator.hasNext()){
            String key = iterator.next().toString();
            if(hasField(fieldList, key)){
                sql += " and "+key+" = '"+ condition.get(key)+"'";
            }
        }
        return sql;
    }

    private boolean hasField(List<TableList.Table.Field> fieldList, String key) {

        List<TableList.Table.Field> list = fieldList.stream()
                .filter(field -> field.getName().equals(key))
                .collect(Collectors.toList());

        if(list.size() > 0){
            return true;
        }

        return false;
    }

}
